package com.swl.juc.queue;

//阻塞队列BlockQueue
class BlockQueue{
    //该队列用一个数组来实现，我们让此队列的最大容量为10
        private int[] items = new int[10];
        private int head = 0;
        private int tail = 0;
        private int size = 0;
        private Object locker =new Object();
        //入队
        public void put(int item) throws InterruptedException {
            synchronized(locker) {
                while (size == items.length) {
                    //入队时，若队满，阻塞
                    locker.wait();
                }
                items[tail++] = item;
                //如果到达末尾，重回队首（实现循环队列）
                if (tail >= items.length) {
                    tail = 0;
                }
                size++;
                locker.notify();
            }
        }

        //出队
        public int back() throws InterruptedException {
            int ret = 0;
            synchronized (locker) {
                while (size == 0) {
                    //出队时，若队空，阻塞
                    locker.wait();
                }
                ret = items[head++];
                if (head >= items.length) {
                    head = 0;
                }
                size--;
                locker.notify();
            }
            return ret;
        }
    public static void main(String[] args) throws InterruptedException {
        BlockQueue blockQueue = new BlockQueue();

        //生产者线程
        Thread produce = new Thread(){
            @Override
            public void run() {
                for(int i = 0;i<10000;++i){

                    try {
                        System.out.println("生产了:"+i);
                        blockQueue.put(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        produce.start();

        //消费者线程
        Thread customer = new Thread(){
            @Override
            public void run() {
                while (true) {
                    try {
                        int res = blockQueue.back();
                        System.out.println("消费了：" + res);

                        //每次消费后等1秒，也就是生产的快，消费的慢
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        customer.start();

        customer.join();
        produce.join();
    }

}
